class InvitationController < ApplicationController
  layout 'login'
  #include ApplicationHelper
  
  def index
    redirect_to :controller=>:welcome
  end
  
  def join
    @join = Invitation.find_by_key(params[:id])
    redirect_to :action=>:error and return if(!@join)
  end
  
  def error    
  end
  
  def add_users
    @project = Project.find(params[:id])
    emails  = params[:invite][:emails].split("\n")
    from = User.find(session['user'])
    name    = params[:invite][:name]
    msg     = params[:invite][:msg]
    
    # search email in the users db
    nb = 0
    str = ''
    emails.each { |e|
      e.strip!
      next if e==''
      # verify if the invitation is already sent
      i = Invitation.find_by_email_and_project_id(e,@project.id)
      if(i)
        str += "invitation for #{e} already exist and will be resent<br/>"
        i.destroy
      end
      
      # try to find the invited
      u = User.find_by_email(e)
      id = u ? u.id : -1
      
      if (u and u.project_ids.member?(@project.id)) # TODO: to test
        str += "user #{u.name} (#{e}) is already a member of this project<br/>"
        next
      end
      
      # generate a key
      key = ApplicationHelper.generate_key
      #logger.info "key=#{key}<br/>"
      
      # create record
      i = Invitation.create(:user_id=>from.id,:name=>name, :msg=>msg, :key=>key, :email=>e, :invited_id=>id, :project_id=>@project.id)
      str += "invitation sent to #{e}<br/>"
      
      #send email
      AppMailer.deliver_invite_users(i,@project,from)
      AppMailer.deliver_alert('invitation',"#{i.to_s}")
      nb += 1
    }
    flash[:notice] = nb.to_s + " email(s) sent<br/>"+str
    redirect_to(:controller=>:project, :action => :edit, :id=>@project)
  end
  
  def accept
    id = params[:id]
    i = Invitation.find(id)
    AppMailer.deliver_invite_result(i, "accepted")
    AppMailer.deliver_alert('invitation accepted',"#{i.to_s}")
    User.find(session['user']).accept_invitation([i]) # delete the invitation
    render(:text=>"You are now member of the project \"<a href=\"/task/select_project_index/#{i.project.id}\">#{i.project.name}</a>\"")
  end
  
  def decline
    id = params[:id]
    i = Invitation.find(id)
    AppMailer.deliver_invite_result(i, "declined")
    AppMailer.deliver_alert('invitation declined',"#{i.to_s}")
    User.find(session['user']).decline_invitation([i]) # delete the invitation
    render(:text=>"You've just declined the invitation.")
  end
end
